package com.sc.VenusQueryBeta.ui.fragments.hotel.child.tabs;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseRecycleFragment;
import com.hengjun.kingstar.sdk.utils.ScreenUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.home.RestaurantAdapter;
import com.sc.VenusQueryBeta.api.Host;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.hotel.tabs.HotelDiningContract;
import com.sc.VenusQueryBeta.model.bean.home.HotelRestaurantBean;
import com.sc.VenusQueryBeta.model.bean.home.VipListBean;
import com.sc.VenusQueryBeta.presenter.hotel.tabs.HotelDiningPresenter;
import com.sc.VenusQueryBeta.ui.widgets.ExpandTextView;

import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;
import cn.carbs.android.expandabletextview.library.ExpandableTextView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

/**
 * Created by Administrator on 25/9/2018.
 * 酒店餐厅fragment
 */

public class HotelDiningFragment extends BaseRecycleFragment<HotelDiningContract.HotelDiningPresenter> implements HotelDiningContract.IHotelDiningView {

    @BindView(R.id.rv_restaurant)
    RecyclerView rvRestaurant;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.hotel_all)
    LinearLayout hotelAll;
    Unbinder unbinder;
    private CustomPopWindow mCustomPopWindow;
    private RestaurantAdapter restaurantAdapter;
    private VipListBean.DataBean.ClubListBean listBean;
    private boolean isUpdate = false;
    private TextView tv_hotel_name, tv_introduce, tv_time, tv_cal_phone, tv_addres;
    private ImageView imageView;
    private cn.carbs.android.expandabletextview.library.ExpandableTextView expandTextView;

    public static HotelDiningFragment newInstance() {
        return new HotelDiningFragment();
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return HotelDiningPresenter.newInstance();
    }

    @Override
    public void updateContentList(List<Object> list) {
    }

    @Override
    public void itemNotifyChanged(int position) {
    }

    @Override
    public void showHotelRestaurantDataSuccess(HotelRestaurantBean hotelRestaurantBean) {
        if (restaurantAdapter.getData().size() == 0) {
            initRecycleview(hotelRestaurantBean);
        } else {
            if (isUpdate) {//
                restaurantAdapter.replaceData(hotelRestaurantBean.getData());
            } else {
                restaurantAdapter.addData(hotelRestaurantBean.getData());
            }
        }
        ptrClass.refreshComplete();//
    }


    @Override
    public void showNetworkError() {

    }

    @Override
    public void showLoadMoreError() {

    }

    @Override
    public void showNoMoreData() {

    }

    /**
     * 當錯誤時，請求回調
     */
    @Override
    protected void onErrorViewClick(View view) {
        mPresenter.getHotelRestaurantData(listBean.getVipClubId());
    }

    @Override
    protected void showLoading() {
        restaurantAdapter.setEmptyView(loadingView);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_hoteldining;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        restaurantAdapter = new RestaurantAdapter(R.layout.item_restauran);
        rvRestaurant.setAdapter(restaurantAdapter);
        rvRestaurant.setLayoutManager(new LinearLayoutManager(mActivity));
        reFreshListener();//监听下拉
    }

    private void showPopTopWithDarkBg(HotelRestaurantBean.DataBean dataBean) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_hotel_popupwindow, null);
        tv_hotel_name = contentView.findViewById(R.id.pop_hotel_name);
        tv_hotel_name.setText(dataBean.getHotelName());

        expandTextView = contentView.findViewById(R.id.pop_introduct);
        expandTextView.setText(dataBean.getBrief());
        // 测试添加OnClickListener的情况，功能正常。添加外部的onClick事件后，原来的点击toggle功能自动屏蔽，
        // 点击尾部的ClickableSpan仍然有效
//        expandTextView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                switch (expandTextView.getExpandState()) {
//                    case ExpandableTextView.STATE_SHRINK:
////                        Toast.makeText(getApplicationContext(),"ExpandableTextView clicked, STATE_SHRINK",
////                                Toast.LENGTH_SHORT).show();
//                        break;
//                    case ExpandableTextView.STATE_EXPAND:
////                        Toast.makeText(getApplicationContext(),"ExpandableTextView clicked, STATE_EXPAND",
////                                Toast.LENGTH_SHORT).show();
//                        break;
//                }
//            }
//        });
//        expandTextView.setText(mPoems[0]);//在ExpandableTextView在创建完成之前改变文字，功能正常
        tv_time = contentView.findViewById(R.id.pop_tv_time);
        tv_time.setText(dataBean.getServiceTime());

        tv_cal_phone = contentView.findViewById(R.id.pop_tv_cal);
        tv_cal_phone.setText(dataBean.getOrderTel());

        tv_addres = contentView.findViewById(R.id.pop_tv_address);
        tv_addres.setText(dataBean.getHotelAddress());

        imageView = contentView.findViewById(R.id.pop_img);
        Glide.with(mContext).load(Host.HostImg + dataBean.getHotelImageUrl()).diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.drawable.load_error).into(imageView);

        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.1f) // 控制亮度
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                    }
                })
                .create()
                .showAtLocation(hotelAll, Gravity.CENTER, 0, 0);
    }

    /**
     * 填充酒店餐廳適配器
     *
     * @param hotelRestaurantBean
     */
    private void initRecycleview(final HotelRestaurantBean hotelRestaurantBean) {
        restaurantAdapter = new RestaurantAdapter(R.layout.item_restauran, hotelRestaurantBean.getData());
        rvRestaurant.setAdapter(restaurantAdapter);

        restaurantAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//           restaurantAdapter
                showPopTopWithDarkBg(hotelRestaurantBean.getData().get(position));

            }
        });
    }

    /**
     * 獲得傳過來的id值
     *
     * @param bundle
     */
    @Override
    public void getBundle(Bundle bundle) {
        if (bundle != null) {
            listBean = (VipListBean.DataBean.ClubListBean) bundle.getSerializable(Constants.VIP_CLUB_LIST);
//            ToastUtils.showToast(listBean.getClubName());
        } else {
//            ToastUtils.showToast("null");
        }
    }

    /**
     * 根據id加載畫面
     *
     * @param savedInstanceState
     */
    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mPresenter.getHotelRestaurantData(listBean.getVipClubId());
    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mActivity);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        restaurantAdapter.notifyDataSetChanged();
                        isUpdate = true;
                        mPresenter.getHotelRestaurantData(listBean.getVipClubId());
                    }
                }, 1000);
            }
        });
    }


}
